package com.labweb.servicos;

import java.math.BigDecimal;
import java.util.List;

import javax.transaction.HeuristicMixedException;
import javax.transaction.HeuristicRollbackException;
import javax.transaction.RollbackException;
import javax.transaction.SystemException;

import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

import com.labweb.entidades.Usuario;
import com.labweb.util.HibernateUtil;


public class UsuarioService {
	public Usuario pesquisarPorId(Integer id) {
		Session session =  HibernateUtil.getSession();
		try {
			return (Usuario) session.get(Usuario.class, id);
		} finally {
			session.close();
		}
	}
	
	public List<Usuario> listarTodas() {
		Session session =  HibernateUtil.getSession();
		try {
			return session.createCriteria(Usuario.class).addOrder(Order.asc("nome")).list();
		} finally {
			session.close();
		}
	}
	
	public Usuario pesquisarPorEmail(String email) {
		Session session =  HibernateUtil.getSession();
		try {
			return (Usuario) session.createCriteria( Usuario.class ).
			           add( Restrictions.eq("email", email) ).
			           uniqueResult();
		} finally {
			session.close();
		}
	}
	
	public void salvar(Usuario usuario) throws Exception, SecurityException, RollbackException, HeuristicMixedException, HeuristicRollbackException, SystemException {
		Session session = (Session) HibernateUtil.getSession();
		Transaction tx = (Transaction) session.beginTransaction();
		session.saveOrUpdate(usuario);
		tx.commit();
		session.close();
	}

	public List<Usuario> listarTodosGestores() {
		// TODO Auto-generated method stub
		Session session =  HibernateUtil.getSession();
		try {
			return session.createCriteria(Usuario.class).add(Restrictions.eq("tipo", 2)).addOrder(Order.asc("nome")).list();
		} finally {
			session.close();
		}
	}

	public void excluir(Usuario usuario) throws Exception, SecurityException, RollbackException, HeuristicMixedException, HeuristicRollbackException, SystemException {
		// TODO Auto-generated method stub
		 
			Session session = (Session) HibernateUtil.getSession();
			Transaction tx = (Transaction) session.beginTransaction();
			session.delete(usuario);
			tx.commit();
			session.close();

		
	}

	public List<Usuario> listarTodosRequerentes() {
		// TODO Auto-generated method stub
		Session session =  HibernateUtil.getSession();
		try {
			return session.createCriteria(Usuario.class).add(Restrictions.eq("tipo", 1)).addOrder(Order.asc("nome")).list();
		} finally {
			session.close();
		}
	}
	
	
	
}
